<template>
	<view class="form-box">
		<view class="login-box">
			<uni-forms class="formContainer" :modelValue="formData" ref="individual">
				<uni-forms-item ref="companyName" name="companyName">
					<view class="form-item">
						<view class="label-box">
							<view class="label-left">
								<text class="label-title">公司名称</text>
								<text class="star">*</text>
							</view>
						</view>
						<view class="item-input" :class="{ placeholder: !formData.companyName }">
							<uni-easyinput :inputBorder="false" type="text" placeholder="请输入公司全称" placehoder
								placeholder-style="color:#999;font-size:28rpx" :clearSize="20"
								@input="searchCompany($event)" @focus.stop="getOptions" @blur="handleBlur"
								v-model="formData.companyName"></uni-easyinput>
						</view>
					</view>
					<view class="mask" @click="closeSelect" v-show="serchList.length && showSelect"></view>
					<view class="optionsBox" data-origin="select" v-show="serchList.length && showSelect">
						<scroll-view scroll-y style="max-height: 240rpx" @scrolltolower="scrolltolower">
							<view class="option" v-for="(option, index) in serchList" :key="index"
								@click.stop="selectCompany(option)">
								<view>{{ option.taxpayerName }}</view>
								<!-- <image v-if="option.creditCode" @click.stop="deleteRecord(option)" class="delete"
                                    src="/static/image/icon/closeDeep.png" /> -->
							</view>
							<view class="loading" v-if="serchList.length && searchLoading">
								<uv-loading-icon :show="searchLoading" text="加载数据中...."></uv-loading-icon>
							</view>
						</scroll-view>
					</view>
				</uni-forms-item>
				<uni-forms-item ref="role" name="role">
					<view class="form-item">
						<view class="label-box">
							<view class="label-left">
								<text class="label-title">申请人身份</text>
								<text class="star">*</text>
							</view>
						</view>
						<view class="item-input">
							<view class="picker-text">
								<picker style="width: 100%;" @change="bindPickerChange" :value="index"
									:range="roleOptions.map(v => v.label)">
									<view class="row100">
										<span
											:style="{ color: formData.role ? '#222' : '', fontSize: formData.role ? '34rpx' : '28rpx' }">
											{{ formData.role ? `${formData.role}` : "请选择申请人身份" }}
										</span>
										<uni-icons type="right" color="#333" size="20" style="line-height: 0;"></uni-icons>
									</view>
								</picker>
							</view>
						</view>
					</view>
				</uni-forms-item>

				<uni-forms-item ref="age" name="age" v-if="current == 2">
					<view class="form-item">
						<view class="label-box">
							<view class="label-left">
								<text class="label-title">申请人年龄</text>
								<text class="star">*</text>
							</view>
						</view>
						<view class="item-input">
							<uni-easyinput :inputBorder="false" type="number" placeholder-style="color:#999;font-size:28rpx"
								:clearSize="20" placeholder="请输入申请人年龄" maxlength="8" v-model="formData.age"></uni-easyinput>
						</view>
					</view>
				</uni-forms-item>
				<view class="btn-box">
					<button class="submit" :loading="loading" :disabled="loading" @click="onSubmit()">
						立即查询
					</button>
					<button class="record" @click="goRecord">历史匹配</button>
					<!-- #ifdef MP-WEIXIN -->
					<button class="share" open-type="share" type="primary">
						分享
					</button>
					<!-- #endif -->
					<!-- #ifdef H5 -->
					<button class="share" @click="openAnthoer" type="primary">
						分享
					</button>
					<!-- #endif -->
				</view>
			</uni-forms>
		</view>
		<authorize :isShowAuth="isShowAuth" @authColse="authColse" @onLoadFun="onLoadFun"></authorize>
	</view>
</template>

<script>
import {
	getSearchList,
	getEnterpriseSearch,
	deleteSearchRecord,
	searchDicListApi,
	shareLoginApi
} from "@/api/product";

import Authorize from "@/components/Authorize.vue";

import { mapGetters } from "vuex";
export default {
	components: {
		Authorize
	},
	props: {
		current: {
			type: Number,
			default: 1,
		},
	},
	// #ifdef MP-WEIXIN
	options: {
		styleIsolation: 'shared' // 解除样式隔离
	},
	// #endif
	computed: mapGetters(["isLogin"]),
	data() {
		return {
			
			roleOptions: [],
			formData: {
				companyName: "",
				role: "",
				age: "",
			},

			loading: false,
			searchLoading: false,
			showSelect: false,
			serchList: [],
			where: {
				keyword: "",
				pageNum: 1,
				total: 0,
			},
			timeoutId: null,
			formRules: {
				companyName: {
					rules: [{
						required: true,
						errorMessage: "公司名称未输入",
					},],
				},
				role: {
					rules: [{
						required: true,
						errorMessage: "申请人身份未选择",
					},],
				},
				age: {
					rules: [{
						required: true,
						errorMessage: "请输入年龄",
					},
					{
						validateFunction: function (rule, value, data, callback) {
							if (value < 18 || value > 100) {
								callback('申请人年龄只支持18~100岁')
							}
						}
					},
					],
				},
			},
			visible: false,

			isShowAuth: false
		};
	},
	onReady() { },
	mounted() {
		this.$refs.individual.setRules(this.formRules);
	},
	created() {
		this.getPickerOptions();
	},
	methods: {
		openAnthoer() {
			this.$emit('openShareLog')
		},
		async onLoadFun() {
			this.isShowAuth - false
			await this.$parent.$parent.doActivity()
		},
		authColse() {
			this.isShowAuth = false;
		},
		goRecord() {
			if (this.isLogin) {
				uni.navigateTo({
					url: '/pagesProduct/matchList/index'
				})
			} else {
				this.isShowAuth = true
			}
		},
		closeSelect() {
			this.showSelect = false;
			this.serchList = []
		},
		bindPickerChange(e) {
			this.formData.role = this.roleOptions[e.detail.value].label;
		},
		onnodeclick(e) {
			this.formData.role = e.text;
		},
		onchange(e) { },
		onClose() {
			this.visible = false
		},
		onOpenShare() {
			this.visible = true
		},
		selectCompany(data) {
			this.formData.companyName = data.taxpayerName;
			this.showSelect = false;
		},
		scrolltolower() {
			if (!this.where.keyword) return;
			if (this.where.pageNum * 10 < this.where.total) {
				this.where.pageNum++;
				this.getSearchList();
			}
		},
		async deleteRecord(option) {
			await deleteSearchRecord(option.id);
			await this.getOptions(); //延安乐升工贸有限公司
		},
		async searchCompany(e) {
			this.serchList = [];
			this.showSelect = true;
			if (e != this.where.keyword) {
				this.serchList = [];
				this.where.pageNum = 1;
			}
			this.where.keyword = e;
			if (e.length > 2) {
				let reg = /^[^\x00-\x7F]*[^\da-zA-Z0-9]*$/;
				const reg2 = /^[^_IOZSVa-z\W]{2}\d{6}[^_IOZSVa-z\W]{10}$/;
				if (!reg.test(e) && !reg2.test(e))
					return this.$util.Tips(`请输入正确的公司名称或税号`);
				clearTimeout(this.timeoutId);
				// 设置新的定时器
				this.timeoutId = setTimeout(() => {
					this.getSearchList();
				}, 500); // 设置防抖的延迟时间（1秒）
			}
		},

		async getSearchList() {
			this.searchLoading = true;
			let res = await getEnterpriseSearch(this.where);
			let data = res.data.list.map((v) => {
				return {
					taxpayerName: v.companyName,
					id: v.establishDate,
				};
			});
			this.serchList = [...this.serchList, ...data];
			this.where.total = res.data.total;
			this.searchLoading = false;
		},
		async getOptions() {
			this.showSelect = true;
			if (!this.where.keyword) {
				let params = {
					keyword: "",
				};
				let res = await getSearchList(params);
				this.serchList = res.data;
			}
		},
		onSubmit() {
			this.$refs.individual.validate().then(async (validate) => {
				const role = this.roleOptions
					.flat()
					.find((v) => v.label == this.formData.role).value;
				this.loading = true;
				shareLoginApi({
					creditCodeName: this.formData.companyName.trim(),
				})
					.then((res) => {
						let params = {
							tax: res.data.creditCodeOrTaxPayerId,
							companyName: res.data.taxpayerName.trim(),
							matchType: 1,
							phoneNumber: res.data?.phoneNumber?.trim(),
							role: role,
							provinceId: res.data.provinceId,
							age: this.formData.age.trim(),
						};
						let url = Object.keys(params).reduce((pre, cur) => {
							return pre + (params[cur] ? `&${cur}=${params[cur]}` : "");
						}, "");
						this.loading = false;

						if (this.current == 1) {
							uni.redirectTo({
								url: `/pagesProduct/addCampanyData/index?${url.substring(
									1,
									url.length
								)}`,
							});
						} else if (this.current == 2) {
							uni.redirectTo({
								url: `/pagesProduct/questionMatch/index?${url.substring(
									1,
									url.length
								)}`,
							});
						}
					})
					.finally(() => {
						this.loading = false;
					});
			});
		},
		async getPickerOptions() {
			let arr = ["person_stand"];
			let res = await searchDicListApi(arr.join(","));
			if (res && res.code == 200) {
				this.roleOptions = res.data.person_stand.map(v => {
					return {
						label: v.dictLabel,
						value: v.dictValue
					}
				});

			}
		},
	},
};
</script>

<style lang="scss">
/deep/ .is-input-border {
	border: none !important;
}

/deep/ .uni-easyinput__content {
	.content-clear-icon {
		line-height: 0;
	}
}

/deep/ .uni-easyinput__content-input {
	padding-left: 0 !important;
	height: 48rpx;
	font-size: 34rpx;
}


.uni-forms-item {
	margin-bottom: 0;
}

.star {
	font-size: 24rpx;
	color: #fa0000;
	font-weight: bold;
	margin-left: 4rpx;
}

.row100 {
	display: flex;
	align-items: center;
	justify-content: space-between;
	width: 100%;
}

.optionsBox {
	position: absolute;
	z-index: 10;
	top: 180rpx;
	left: 0rpx;
	padding: 30rpx 20rpx;
	width: 100%;
	border-radius: 10rpx;
	background-color: #ffffff;
	border: 1px solid #ebeef5;
	overflow-y: scroll;

	.option {
		line-height: 40rpx;
		margin-bottom: 30rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;

		&:last-child {
			margin-bottom: 0rpx;
		}

		.delete {
			width: 30rpx;
			height: 30rpx;
		}
	}
}

.form-box {
	padding: 0 30rpx 115rpx;
	background-color: #fff;
	border-radius: 0 0 20rpx 20rpx;
}

.login-box {
	.form-item {
		padding-top: 60rpx;

		.label-box {
			display: flex;
			align-items: center;
			justify-content: space-between;

			.label-left {
				display: flex;
				align-items: center;

				.label-title {
					font-weight: 600;
					font-size: 30rpx;
					color: #333333;
					line-height: 42rpx;
				}
			}

		}

		.item-input {
			border-bottom: 1rpx solid #EDEDED;
			padding-bottom: 30rpx;
			font-size: 34rpx;
			line-height: 48rpx;
			margin-top: 10rpx;
		}
	}

}

.btn-box {
	// display: flex;
	margin-top: 85rpx;

	button {
		display: inline-block;
		line-height: 88rpx;
		font-weight: 600;
		height: 88rpx;
		border-radius: 12rpx;
		font-size: 34rpx;
	}

	.submit {
		background: #276ff7;
		color: #ffffff;
		width: 100%;
	}

	.share,
	.record {
		background: #fff;
		margin-top: 30rpx;
		color: #2872FD;
		border: 2rpx solid #2872FD;
	}

	.record {
		width: 468rpx;
	}

	.share {
		width: 144rpx;
		margin-left: 18rpx;
	}
}

.picker-text {
	display: flex;
	justify-content: space-between;
	font-weight: 400;
	font-size: 34rpx;
	color: #999;
	width: 100%;

}

.activeValue {
	color: #333;
}

/deep/.is-input-error-border .uni-easyinput__placeholder-class {
	color: #999 !important;
}
</style>